<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <!-- 普通用户只显示开具日期查询条件 -->
      <template v-if="!isNormalUser">
        <el-form-item label="生产主体" prop="productionEntity">
          <el-input
            v-model="queryParams.productionEntity"
            placeholder="请输入生产主体"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="注册手机号" prop="mobilePhone">
          <el-input
            v-model="queryParams.mobilePhone"
            placeholder="请输入手机号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
      </template>
      
      <!-- 管理员显示所有查询条件，监管者不显示省市区 -->
      <template v-if="isAdmin">
        <el-form-item label="省" prop="province">
          <el-select v-model="queryParams.province" placeholder="请选择省" clearable @change="handleProvinceChange">
            <el-option
              v-for="province in provinceOptions"
              :key="province.value"
              :label="province.label"
              :value="province.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="市" prop="city">
          <el-select v-model="queryParams.city" placeholder="请选择市(请先选择省)" clearable @change="handleCityChange">
            <el-option
              v-for="city in cityOptions"
              :key="city.value"
              :label="city.label"
              :value="city.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="区/县" prop="district">
          <el-select v-model="queryParams.district" placeholder="请选择区/县(请先选择市)" clearable>
            <el-option
              v-for="district in districtOptions"
              :key="district.value"
              :label="district.label"
              :value="district.value"
            />
          </el-select>
        </el-form-item>
      </template>
      
      <!-- 监管者和普通用户显示乡镇/街道查询条件 -->
      <el-form-item v-if="!isAdmin" label="乡镇/街道" prop="township">
        <el-select v-model="queryParams.township" placeholder="请选择乡镇/街道" clearable>
          <el-option
            v-for="township in townshipOptions"
            :key="township.value"
            :label="township.label"
            :value="township.value"
          />
        </el-select>
      </el-form-item>
      
      <!-- 所有用户都显示开具日期查询条件 -->
      <el-form-item label="开具日期" prop="issuanceDate">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 角色权限说明 -->
    <div v-if="showSearch" class="role-permission-tips">
      <el-alert
        title="查询条件权限说明"
        type="info"
        :closable="false"
        show-icon>
        <div slot="description">
          <p><strong>管理员:</strong> 显示所有查询条件</p>
          <p><strong>监管者:</strong> 不显示省市区查询条件</p>
          <p><strong>普通用户:</strong> 只显示开具日期查询条件</p>
        </div>
      </el-alert>
    </div>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['nongjt:certificateIssuanceStats:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5" v-if="isAdmin">
        <el-button
          type="success"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleRefreshStats"
          v-hasPermi="['nongjt:certificateIssuanceStats:refresh']"
        >刷新统计</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="certificateIssuanceStatsList" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="生产主体" align="center" prop="productionEntity" min-width="200" show-overflow-tooltip />
      <el-table-column label="法人姓名" align="center" prop="legalPersonName" min-width="120" />
      <el-table-column label="注册手机号" align="center" prop="mobilePhone" min-width="130" />
      <el-table-column label="省" align="center" prop="province" min-width="100" />
      <el-table-column label="市" align="center" prop="city" min-width="100" />
      <el-table-column label="区/县" align="center" prop="district" min-width="100" />
      <el-table-column label="镇/乡" align="center" prop="township" min-width="120" />
      <el-table-column label="产品数量" align="center" prop="productCount" min-width="100">
        <template slot-scope="scope">
          <el-tag type="primary">{{ scope.row.productCount }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="开具数量" align="center" prop="issuanceCount" min-width="100">
        <template slot-scope="scope">
          <el-tag type="success">{{ scope.row.issuanceCount }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="总数量/重量(公斤)" align="center" prop="totalWeight" min-width="150">
        <template slot-scope="scope">
          <el-tag type="warning">{{ formatWeight(scope.row.totalWeight) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="统计日期" align="center" prop="statsDate" min-width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.statsDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 刷新统计对话框 -->
    <el-dialog title="刷新统计数据" :visible.sync="refreshOpen" width="500px" append-to-body>
      <el-form ref="refreshForm" :model="refreshForm" :rules="refreshRules" label-width="120px">
        <el-form-item label="统计日期" prop="statsDate">
          <el-date-picker
            v-model="refreshForm.statsDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择统计日期"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="日期范围" prop="dateRange">
          <el-date-picker
            v-model="refreshForm.dateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRefresh">确 定</el-button>
        <el-button @click="cancelRefresh">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCertificateIssuanceStats, exportCertificateIssuanceStats, refreshStats, batchGenerateStats } from "@/api/monitor/njt/certificate/issuanceStats";

export default {
  name: "CertificateIssuanceStats",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合格证开具数量统计表格数据
      certificateIssuanceStatsList: [],
      // 是否显示刷新统计弹出层
      refreshOpen: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productionEntity: null,
        mobilePhone: null,
        province: null,
        city: null,
        district: null,
        township: null
      },
      // 刷新表单参数
      refreshForm: {
        statsDate: null,
        dateRange: []
      },
      // 刷新表单校验
      refreshRules: {
        statsDate: [
          { required: true, message: "统计日期不能为空", trigger: "change" }
        ]
      },
      // 省市区选项
      provinceOptions: [
        { label: '四川省', value: '四川省' }
      ],
      cityOptions: [],
      districtOptions: [],
      townshipOptions: [],
      // 用户类型判断
      isAdmin: true,
      isNormalUser: false
    };
  },
  created() {
    this.getList();
    this.initRegionData();
    this.checkUserType();
  },
  methods: {
    /** 查询合格证开具数量统计列表 */
    getList() {
      this.loading = true;
      listCertificateIssuanceStats(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.certificateIssuanceStatsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('nongjt/certificateIssuanceStats/export', {
        ...this.queryParams
      }, `合格证开具数量统计_${new Date().getTime()}.xlsx`)
    },
    /** 刷新统计按钮操作 */
    handleRefreshStats() {
      this.refreshForm = {
        statsDate: null,
        dateRange: []
      };
      this.refreshOpen = true;
    },
    /** 提交刷新统计 */
    submitRefresh() {
      this.$refs["refreshForm"].validate(valid => {
        if (valid) {
          if (this.refreshForm.dateRange && this.refreshForm.dateRange.length === 2) {
            // 批量刷新
            batchGenerateStats(this.refreshForm.dateRange[0], this.refreshForm.dateRange[1]).then(response => {
              this.$modal.msgSuccess(response.msg);
              this.refreshOpen = false;
              this.getList();
            });
          } else if (this.refreshForm.statsDate) {
            // 单日刷新
            refreshStats(this.refreshForm.statsDate).then(response => {
              this.$modal.msgSuccess(response.msg);
              this.refreshOpen = false;
              this.getList();
            });
          } else {
            this.$modal.msgError("请选择统计日期或日期范围");
          }
        }
      });
    },
    /** 取消刷新统计 */
    cancelRefresh() {
      this.refreshOpen = false;
      this.resetRefreshForm();
    },
    // 刷新表单重置
    resetRefreshForm() {
      this.refreshForm = {
        statsDate: null,
        dateRange: []
      };
      this.resetForm("refreshForm");
    },
    // 格式化重量显示
    formatWeight(weight) {
      if (!weight) return '0';
      const num = parseFloat(weight);
      if (num >= 1000) {
        return (num / 1000).toFixed(2) + '吨';
      } else if (num >= 1) {
        return num.toFixed(2) + 'kg';
      } else {
        return (num * 1000).toFixed(0) + 'g';
      }
    },
    // 初始化地区数据
    initRegionData() {
      // 这里应该从后端获取地区数据，暂时使用模拟数据
      this.cityOptions = [
        { label: '成都市', value: '成都市' }
      ];
      this.districtOptions = [
        { label: '郫都区', value: '郫都区' },
        { label: '新都区', value: '新都区' },
        { label: '温江区', value: '温江区' },
        { label: '天府新区', value: '天府新区' },
        { label: '青白江区', value: '青白江区' }
      ];
      this.townshipOptions = [
        { label: '郫筒街道', value: '郫筒街道' },
        { label: '安德街道', value: '安德街道' },
        { label: '新桥街道', value: '新桥街道' },
        { label: '德源街道', value: '德源街道' },
        { label: '煎茶街道', value: '煎茶街道' },
        { label: '唐昌镇', value: '唐昌镇' },
        { label: '永兴街道', value: '永兴街道' },
        { label: '青白江区本级', value: '青白江区本级' }
      ];
    },
    // 检查用户类型
    checkUserType() {
      // 这里应该根据当前登录用户判断用户类型
      // 暂时使用模拟数据
      this.isAdmin = true; // 管理员
      this.isNormalUser = false; // 普通用户
    },
    // 省变化处理
    handleProvinceChange(value) {
      this.queryParams.city = null;
      this.queryParams.district = null;
      // 根据省加载市数据
    },
    // 市变化处理
    handleCityChange(value) {
      this.queryParams.district = null;
      // 根据市加载区县数据
    }
  }
};
</script>

<style scoped>
.role-permission-tips {
  margin-bottom: 20px;
}

.role-permission-tips .el-alert {
  margin-bottom: 0;
}

.role-permission-tips p {
  margin: 5px 0;
  font-size: 14px;
}
</style>
